﻿/*
Copyright (c) 2013, Douglas Stebila, Brendon Park, David Sweeney, Nathan Wills, Simon Lockhart, Thomas Phan
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this
  list of conditions and the following disclaimer in the documentation and/or
  other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;

namespace NMLE
{

    /// <summary>
    ///     Message locked encryption algorythm provides conistant cryptotext
    ///     by derving the encryption key from the contents of the message. 
    /// </summary>
    /// <typeparam name="THashAlgorithm">
    ///     The hash algorythm used to produce the keys used to encrypt the
    ///     message.
    /// </typeparam>
    /// <typeparam name="TEncryptionAlgorithm">
    ///     The cryptographic algorytm used to produce the cyphertext.
    /// </typeparam>
    public abstract class MessageLockedAlgoritm
        <THashAlgorithm, TEncryptionAlgorithm> : IMessageLockedAlgorithm
        where THashAlgorithm : HashAlgorithm, new()
        where TEncryptionAlgorithm : SymmetricAlgorithm, new() 
    {

        protected THashAlgorithm HashInstance;
        protected TEncryptionAlgorithm CryptoInstance;

        /// <summary>
        ///     Intialises base members of a message locked algorythm.
        /// </summary>
        /// <exception cref="IncompatableAlgorithmException">
        ///     Thrown when the output length of <see cref="THashAlgorithm" />
        ///     is less than the smallest allowed TransformKey or IV length
        /// </exception>
        protected MessageLockedAlgoritm()
        {
            HashInstance = new THashAlgorithm();
            CryptoInstance = new TEncryptionAlgorithm();

            LegalKeySizes = GetLegalKeySizeses();
            if (LegalKeySizes.Length < 1)
                throw new IncompatableAlgorithmException(
                    HashInstance,CryptoInstance
                );

            KeySize = LargestValidKey();
        }

        /// <summary>
        ///     Gets or sets the block size, in bits, of the cryptographic
        ///     operation.
        /// </summary>
        public int BlockSize
        {
            get { return CryptoInstance.BlockSize; }
            set { CryptoInstance.BlockSize = value; }
        }

        /// <summary>
        ///     Gets or sets the feedback size, in bits, of the cryptographic
        ///     operation.
        /// </summary>
        public int FeedbackSize
        {
            get { return CryptoInstance.FeedbackSize; }
            set { CryptoInstance.FeedbackSize = value; }
        }

        /// <summary>
        ///     Gets or sets the keysize used
        /// </summary>
        public int KeySize
        {
            get { return CryptoInstance.KeySize; }
            set
            {
                if (!IsValidKeySize(value))
                    throw new ArgumentException(
                        "The supplied keysize is invalid for this algorithm " +
                        "combination"
                        );
                CryptoInstance.KeySize = value;
            }
        }

        /// <summary>
        ///     Gets the key sizes, in bits, that are supported by the
        ///     symmetric algorithm.
        /// </summary>
        public KeySizes[] LegalKeySizes
        {
            get; protected set;
        }

        /// <summary>
        ///     Gets the mode for operation of the symmetric algorithm.
        /// </summary>
        public CipherMode Mode
        {
            get { return CryptoInstance.Mode; }
            set { CryptoInstance.Mode = value; }
        }

        /// <summary>
        ///     Gets the padding mode used in the symmetric algorithm.
        /// </summary>
        public PaddingMode Padding
        {
            get { return CryptoInstance.Padding; }
            set { CryptoInstance.Padding = value; }
        }

        /// <summary>
        ///     Creates a message locked decryptor object with the current
        ///     key, hash algorythm and, symetric algorythm.
        /// </summary>
        /// <returns>
        ///     A message locked decryptor object.
        /// </returns>
        public abstract ICryptoTransform GetDecryptor();

        /// <summary>
        ///     Creates a message locked encryptor object with the current
        ///     hash algorythm and symetric algorythm.
        /// </summary>
        /// <returns>
        /// </returns>
        public abstract ICryptoTransform GetEncryptor();

        /// <summary>
        ///     Gets the MLE key for the given message     
        /// </summary>
        /// <param name="message">
        ///     Stream containing the message that will be encrypted
        /// </param>
        /// <param name="keySize">
        ///     A valid keysize to truncate the key too
        /// </param>
        public abstract void DeriveKey(Stream message, Int32 keySize);

        /// <summary>
        ///     Gets the MLE key for the given message
        /// </summary>
        /// <param name="message">
        ///     Stream containing the message that will be encrypted
        /// </param>
        public abstract void DeriveKey(Stream message);

        /// <summary>
        ///     Gets or sets the secret key for the message locked crypto
        ///     algorithm.
        /// </summary>
        public abstract byte[] Key
        {
            get;set;
        }

        /// <summary>
        ///     Gets the expected tag for the supplied TransformKey
        /// </summary>
        public abstract byte[] Tag
        {
            get;
            protected set;
        }

        /// <summary>
        ///     Performs application-defined tasks associated with freeing,
        ///     releasing, or resetting unmanaged resources.
        /// </summary>
        /// <filterpriority>2</filterpriority>
        public void Dispose()
        {
            CryptoInstance.Dispose();
            HashInstance.Dispose();
        }

        /// <summary>
        ///     Get a value indicating the largest legal keysize
        /// </summary>
        /// <returns>
        ///     The largest legal keysize
        /// </returns>
        public Int32 LargestValidKey()
        {
            return LegalKeySizes.Max(ks => ks.MaxSize);
        }

        private KeySizes[] GetLegalKeySizeses()
        {
            var validSizes = ListValidSizes();

            if (validSizes.Count == 0)
                return null;

            var legalSizes = BuildKeySizes(validSizes);

            return legalSizes.ToArray();
        }

        private static List<KeySizes> BuildKeySizes(
            List<Int32> validSizes
            )
        {
            if (validSizes.Count == 1)
                return new List<KeySizes>
                {
                    new KeySizes(validSizes[0], validSizes[0], 0)
                };

            validSizes.Sort();
            
            var legalSizes = new List<KeySizes>();

            var sizes = new Queue<Int32>(validSizes);

            int lastMin = sizes.Dequeue(),
               lastDiff = sizes.Peek() - lastMin,
               lastSize = lastMin;

            while (sizes.Count > 1)
            {
                int keySize = sizes.Dequeue(),
                       diff = sizes.Peek() - keySize;

                if (diff == lastDiff)
                {
                    lastSize = keySize;
                    continue;
                }

                legalSizes.Add(new KeySizes(
                    lastMin, 
                    lastSize, 
                    lastMin - lastSize > 0 ? lastDiff : 0)
                    );

                lastDiff = diff;
                lastMin = keySize;

            }

            legalSizes.Add(
                new KeySizes(
                    lastMin, 
                    sizes.Dequeue(), 
                    lastMin - lastSize > 0 ? lastDiff : 0
                    )
                );

            return legalSizes;
        }

        private List<Int32> ListValidSizes()
        {
            List<Int32> validKeySizes = new List<Int32>(),
                validSizes = new List<Int32>();

            foreach (var keySize in CryptoInstance.LegalKeySizes)
                for (int i = keySize.MinSize;
                    i <= keySize.MaxSize; 
                    i = i + (keySize.SkipSize==0 ? 1 :keySize.SkipSize))
                        validKeySizes.Add(i);

            foreach (var keySize in CryptoInstance.LegalBlockSizes)
                for (int i = keySize.MinSize;
                    i <= keySize.MaxSize;
                    i = i + (keySize.SkipSize == 0 ? 1 : keySize.SkipSize))
                    if (validKeySizes.Contains(i) && i <= HashInstance.HashSize)
                        validSizes.Add(i);

            return validSizes;
        }

        private bool IsValidKeySize(int value)
        {
            return value <= HashInstance.HashSize 
                && ListValidSizes().Contains(value);
        }
    }
}